<template>
  <div class="auth-container fade-in">
    <div class="auth-card content-stagger">
      <h2 class="auth-title scale-in">登录</h2>
      <form class="auth-form" @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            type="text"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            class="form-input"
            :class="{ 'is-invalid': errors.username }"
            @blur="validateField('username')"
          />
          <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
            class="form-input"
            :class="{ 'is-invalid': errors.password }"
            @blur="validateField('password')"
          />
          <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
        </div>

        <div class="form-group checkbox-group">
          <label class="checkbox-label">
            <input type="checkbox" v-model="rememberMe" />
            <span>记住我</span>
          </label>
        </div>

        <button type="submit" class="btn btn-primary">登录</button>

        <div class="form-footer">
          <button type="button" class="btn-link" @click="navigateToRegister()">立即注册</button>
          <button type="button" class="btn-link" @click="forgotPassword()">忘记密码</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { storeToRefs } from 'pinia'

const router = useRouter()
const userStore = useUserStore()
const { isLoggedIn } = storeToRefs(userStore)

const loginForm = ref({
  username: '',
  password: '',
})
const rememberMe = ref(false)
const errors = reactive({})

// 自定义消息队列
const messages = ref([])
let messageId = 0

// 添加消息
const showMessage = (message, type = 'success', duration = 3000) => {
  const id = messageId++
  messages.value.push({
    id,
    message,
    type,
    show: false,
  })

  // 确保DOM已更新
  nextTick(() => {
    const msg = messages.value.find((m) => m.id === id)
    if (msg) {
      msg.show = true

      setTimeout(() => {
        msg.show = false
        setTimeout(() => {
          messages.value = messages.value.filter((m) => m.id !== id)
        }, 300)
      }, duration)
    }
  })
}

// 表单验证
const validateField = (field) => {
  errors[field] = ''
  if (field === 'username' && !loginForm.value.username.trim()) {
    errors[field] = '请输入用户名'
  }
  if (field === 'password') {
    if (!loginForm.value.password) {
      errors[field] = '请输入密码'
    } else if (loginForm.value.password.length < 6) {
      errors[field] = '密码长度不能少于6位'
    }
  }
}

const validateForm = () => {
  let isValid = true
  Object.keys(loginForm.value).forEach((field) => {
    validateField(field)
    if (errors[field]) {
      isValid = false
    }
  })
  return isValid
}

const handleLogin = async () => {
  if (!validateForm()) {
    return
  }

  try {
    const success = await userStore.login(loginForm.value)
    if (success) {
      showMessage('登录成功', 'success')
      // 等待状态更新完成后再跳转
      await nextTick()

      // 获取redirect参数
      const redirect = router.currentRoute.value.query.redirect
      // 如果有redirect参数，则跳转到该页面，否则跳转到首页
      if (redirect) {
        await router.push(redirect)
      } else {
        await router.push('/')
      }
    }
  } catch (error) {
    showMessage('登录失败: ' + (error.message || '未知错误'), 'error')
  }
}

const navigateToRegister = () => {
  router.push('/register')
}

const forgotPassword = () => {
  showMessage('忘记密码功能稍后实现', 'info')
}

const toHome = () => {
  router.push('/')
}


</script>

<style scoped>
.auth-container {
  /* background: linear-gradient(135deg, #f8fff8 0%, #f0f9f0 100%); */
  display: flex;
  align-items: center;
  justify-content: center;
}

.auth-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(39, 174, 96, 0.15);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  border: 1px solid rgba(39, 174, 96, 0.1);
  text-align: center;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  cursor: pointer;
}

.music-icon {
  width: 32px;
  height: 32px;
  color: var(--success-color);
  margin-right: 10px;
}

.logo span {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.auth-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  text-align: left;
}

.form-group label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
}

.form-input {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: white;
}

.form-input:focus {
  outline: none;
  border-color: var(--success-color);
  box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.1);
}

.form-input.is-invalid {
  border-color: #ff4757;
}

.error-message {
  color: #ff4757;
  font-size: 14px;
  margin-top: 4px;
}

.checkbox-group {
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.checkbox-label input[type='checkbox'] {
  margin: 0;
}

.btn {
  padding: 14px 28px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #27ae60, #2ecc71);
  color: white;
  box-shadow: 0 4px 15px rgba(39, 174, 96, 0.3);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(39, 174, 96, 0.4);
}

.form-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.btn-link {
  background: none;
  border: none;
  color: var(--success-color);
  cursor: pointer;
  font-size: 14px;
  text-decoration: underline;
}

.btn-link:hover {
  color: #218c54;
}

@media (max-width: 768px) {
  .auth-card {
    padding: 30px 20px;
    margin: 20px;
  }

  .form-footer {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
